package com.itboye.api.helper;

import com.itboye.system.helper.ByConsoleHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * WebFileHelper.java
 * Created on  2016/8/2 15:50
 * 版本       修改时间          作者      修改内容
 * V1.0.1    2016/8/2      hebidu    初始版本
 * <p>
 * Copyright (c) 2013 杭州博也网络科技有限公司 版权所有
 * HANGZHOU BOYE TECHNOLOGY CO.,LTD. All Rights Reserved.
 */
public class WebFileHelper {

    public static void writeDefaultPicture(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("image/png");
        String defaultPic = "404_1.png";
        String realPath = request.getSession().getServletContext().getRealPath("");
        realPath = realPath + "/static/icon/" + defaultPic;
        File file = new File(realPath);

        if(file.exists() && file.canRead()){
            writeFile(file,response);
        }else{
            ByConsoleHelper.info("返回默认图片不存在或不可读",null);
        }


    }

    public static void writeFile(File file, HttpServletResponse response){
        OutputStream outputStream = null;
        byte[] bytes = new byte[1024];
        int len = 0;

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            while ((len = fileInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
